<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="680"
    v-model="visible"
    :title="actionConfigs[action].title"
    @open="handleOpen"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="currentRules"
      label-width="80px"
      @submit.prevent=""
    >
      <el-row :gutter="16">
        <el-col :sm="12" :xs="24">
          <el-form-item label="所属机构">
            <organization-select v-model="form.organization_id" />
          </el-form-item>
          <el-form-item label="用户账号" prop="username">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.username"
              placeholder="请输入用户账号"
              :disabled="disabledFields.includes('username')"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="nickname">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.nickname"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <dict-data code="sex" v-model="form.sex" placeholder="请选择性别" />
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <role-select v-model="form.roles" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              clearable
              :maxlength="100"
              v-model="form.email"
              placeholder="请输入邮箱"
            />
          </el-form-item>
        </el-col>
        <el-col :sm="12" :xs="24">
          <el-form-item label="手机号" prop="phone">
            <el-input
              clearable
              :maxlength="11"
              v-model="form.phone"
              placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
              v-model="form.birthday"
              value-format="YYYY-MM-DD"
              placeholder="请选择出生日期"
              class="ele-fluid"
            />
          </el-form-item>
          <el-form-item v-if="action == 'add'" label="登录密码" prop="password">
            <el-input
              show-password
              type="password"
              :maxlength="20"
              v-model="form.password"
              placeholder="请输入登录密码"
            />
          </el-form-item>
          <el-form-item label="工号" prop="job_number">
            <el-input
              clearable
              :maxlength="100"
              v-model="form.job_number"
              placeholder="请输入工号"
            />
          </el-form-item>
          <el-form-item label="状态">
            <dict-data
              code="status"
              type="radio"
              v-model="form.status"
              placeholder="请选择状态"
            />
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input
              type="textarea"
              :rows="3"
              :maxlength="200"
              v-model="form.introduction"
              placeholder="请输入个人简介"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ actionConfigs[action].button }}
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { emailReg, phoneReg } from "ele-admin-plus/es";
import RoleSelect from "./role-select.vue";
import OrganizationSelect from "@/views/system/organization/components/organization-select.vue";
import {
  addUser,
  updateUser,
  getUser,
  checkExistence,
} from "@/api/system/user";

const props = defineProps({
  action: {
    type: String,
    default: "edit",
    validator: (value) =>
      ["add", "edit", "audit", "push", "view"].includes(value),
  },
  /** 修改回显的数据 */
  data: Object,
  /** 添加时机构id */
  organization_id: Number,
});

/** 表单验证规则 */

import { useFormEdit } from "@/hooks/useFormEdit";

const emit = defineEmits(["update:modelValue", "done", "open"]);

const actionConfigs = {
  add: {
    title: "新增字典数据",
    button: "新增",
    api: addUser,
    showFields: ["dict_data_name", "dict_data_code", "sort_number", "comments"],
    disabledFields: [],
    rules: {
      username: [
        {
          required: true,
          message: "请输入用户账号",
          type: "string",
          trigger: "blur",
        },
        {
          min: 4,
          message: "账号长度最少为4位",
          type: "string",
          trigger: "blur",
        },
        {
          type: "string",
          trigger: "blur",
          validator: (_rule, value, callback) => {
            if (props.action != "add") {
              callback();
              return;
            }
            checkExistence("username", value)
              .then(() => {
                callback(new Error("账号已经存在"));
              })
              .catch(() => {
                callback();
              });
          },
        },
      ],
      nickname: [
        {
          required: true,
          message: "请输入用户名",
          type: "string",
          trigger: "blur",
        },
      ],
      sex: [
        {
          required: true,
          message: "请选择性别",
          type: "number",
          trigger: "change",
        },
      ],
      roles: [
        {
          required: true,
          message: "请选择角色",
          type: "array",
          trigger: "change",
        },
      ],
      email: [
        {
          pattern: emailReg,
          message: "邮箱格式不正确",
          type: "string",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入登录密码",
          type: "string",
          trigger: "blur",
        },
        {
          type: "string",
          trigger: "blur",
          validator: (_rule, value, callback) => {
            if (props.action == "edit" || /^[\S]{5,18}$/.test(value)) {
              return callback();
            }
            callback(new Error("密码必须为5-18位非空白字符"));
          },
        },
      ],
      phone: [
        {
          required: true,
          message: "请输入手机号",
          type: "string",
          trigger: "blur",
        },
        {
          pattern: phoneReg,
          message: "手机号格式不正确",
          type: "string",
          trigger: "blur",
        },
      ],
    },
    beforeOpen: async ({ type, formData }) => {
      // 打开前的操作，可以修改表单数据
      console.log("打开前的操作");
      formData.organization_id = props.organization_id;
      return { type, formData }; // 必须返回处理后的表单数据
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      formData.organization_id = props.organization_id;
      console.log("提交数据:", formData);

      // if (!formData.requiredField) {
      // return Promise.reject(new Error("缺少必填字段")); // 返回rejected Promise中断流程
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  edit: {
    title: "修改字典数据",
    button: "保存",
    api: updateUser, // 补充edit的API
    showFields: ["dict_data_name", "dict_data_code", "sort_number", "comments"],
    disabledFields: ["username"],
    rules: {
      username: [
        {
          required: true,
          message: "请输入用户账号",
          type: "string",
          trigger: "blur",
        },
        {
          min: 4,
          message: "账号长度最少为4位",
          type: "string",
          trigger: "blur",
        },
      ],
      nickname: [
        {
          required: true,
          message: "请输入用户名",
          type: "string",
          trigger: "blur",
        },
      ],
      sex: [
        {
          required: true,
          message: "请选择性别",
          type: "number",
          trigger: "change",
        },
      ],
      roles: [
        {
          required: true,
          message: "请选择角色",
          type: "array",
          trigger: "change",
        },
      ],
      email: [
        {
          pattern: emailReg,
          message: "邮箱格式不正确",
          type: "string",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入登录密码",
          type: "string",
          trigger: "blur",
        },
        {
          type: "string",
          trigger: "blur",
          validator: (_rule, value, callback) => {
            if (props.action == "edit" || /^[\S]{5,18}$/.test(value)) {
              return callback();
            }
            callback(new Error("密码必须为5-18位非空白字符"));
          },
        },
      ],
      phone: [
        {
          required: true,
          message: "请输入手机号",
          type: "string",
          trigger: "blur",
        },
        {
          pattern: phoneReg,
          message: "手机号格式不正确",
          type: "string",
          trigger: "blur",
        },
      ],
    },
    beforeSubmit: async ({ type, formData }) => {
      // 提交前的操作，可以修改表单数据
      formData.organization_id = props.organization_id;
      console.log("提交数据:", formData);
      // // 添加实际验证逻辑
      // if (
      //   !formData.dict_data_name ||
      //   !formData.dict_data_code ||
      //   !formData.sort_number
      // ) {
      // return Promise.reject(new Error("请填写所有必填字段"));
      // }
      return { type, formData }; // 必须返回处理后的表单数据
    },
  },
  view: {
    title: "查看字典数据",
    button: "确定",
    // api: showDictionaryData, // 补充view的API
    showFields: ["dict_data_name", "dict_data_code", "sort_number", "comments"],
    disabledFields: [
      "dict_data_name",
      "dict_data_code",
      "sort_number",
      "comments",
    ],
    rules: {},
  },
};

const {
  form,
  formRef,
  visible,
  loading,
  handleOpen,
  handleSubmit,
  disabledFields,
  currentRules,
  handleCancel,
} = useFormEdit(props, emit, {
  actionConfigs,
  formFields: {
    user_id: void 0,
    username: "",
    nickname: "",
    sex: void 0,
    roles: [],
    email: "",
    phone: "",
    password: "",
    introduction: "",
    birthday: "",
    job_number: "",
    organization_id: props.organization_id,
    status: 0,
  },
  detailApi: getUser,
  idField: "user_id",
});
</script>
